package org.heart.thirdService.hefengAPI.service;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.ibatis.annotations.Param;
import org.heart.thirdService.hefengAPI.req.DailyWeather;
import org.heart.thirdService.hefengAPI.req.HourlyWeather;
import org.heart.thirdService.hefengAPI.req.Location;
import org.heart.thirdService.hefengAPI.req.NowWeather;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static org.heart.utils.HttpUtils.doGet;

@Service
@Slf4j
public class HeFengApiServiceImpl implements HeFengApiService {

    @Value("${hefeng.apiKey}")
    private String apiKy;

    @Value("${hefeng.host}")
    private String heFengHost;

    /**
     * 查询当天天气预报
     */
    @Value("${hefeng.api1}")
    private String api;

    /**
     * 查询七天天气预报
     */
    @Value("${hefeng.api2}")
    private String api2;

    /**
     * 查询24h时段天气预报
     */
    @Value("${hefeng.api3}")
    private String api3;

    @Value("${hefeng.api4}")
    private String api4;

    @Override
    public NowWeather getNowWeather(String location) {

        Map<String,String> header = new HashMap<String,String>();
        header.put("X-QW-Api-Key",apiKy);

        Map<String,String> query = new HashMap<String,String>();
        query.put("location", location);

        log.info("请求配置信息： host:{},path:{},apiKy:{},apiKy:{}",heFengHost,api,apiKy,location);

        try {
            HttpResponse response = doGet(heFengHost,api,header,query);

            Map<String, Object> resultMap = JSON.parseObject(EntityUtils.toString(response.getEntity()), Map.class);

            NowWeather data = new NowWeather();

            data = BeanUtil.copyProperties(resultMap.get("now"),NowWeather.class);

            log.info("网络请求成功！请求响应码为：{},响应结果值为：{}",resultMap.get("code"),resultMap.get("now"));

            return data;

        } catch (Exception e) {
            log.info("网络请求失败！请求api为{}，请求头{}，请求参数{},错误信息为：{}",api,header,query,e.getMessage());
        }

        return null;
    }

    @Override
    public List<DailyWeather> get7DayWeather(String location) {

        Map<String,String> header = new HashMap<String,String>();
        header.put("X-QW-Api-Key",apiKy);

        Map<String,String> query = new HashMap<String,String>();
        query.put("location", location);

        log.info("请求配置信息： host:{},path:{},apiKy:{},apiKy:{}",heFengHost,api2,apiKy,location);

        try {
            HttpResponse response = doGet(heFengHost,api2,header,query);

            // 1. 解析 JSON 数据
            Map<String, Object> resultMap = JSONUtil.parseObj(EntityUtils.toString(response.getEntity()));

            // 2. 获取 daily 数据（假设 daily 是一个 List<Map>）
            List<Map<String, Object>> dailyList = (List<Map<String, Object>>) resultMap.get("daily");

            // 3. 使用 Hutool 的 BeanUtil 转换
            List<DailyWeather> list = dailyList.stream()
                    .map(dailyMap -> BeanUtil.toBean(dailyMap, DailyWeather.class))
                    .collect(Collectors.toList());

            log.info("网络请求成功！请求响应码为：{},响应结果值为：{}",resultMap.get("code"),resultMap.get("daily"));

            return list;

        } catch (Exception e) {
            System.out.println(e);
            log.info("网络请求失败！请求api为{}，请求头{}，请求参数{},错误信息为：{}",api2,header,query,e.getMessage());
        }

        return Collections.emptyList();
    }

    @Override
    public List<HourlyWeather> getHourDuanWeather(String location) {

        Map<String,String> header = new HashMap<String,String>();
        header.put("X-QW-Api-Key",apiKy);

        Map<String,String> query = new HashMap<String,String>();
        query.put("location", location);

        log.info("请求配置信息： host:{},path:{},apiKy:{},apiKy:{}",heFengHost,api3,apiKy,location);

        try {
            HttpResponse response = doGet(heFengHost,api3,header,query);

            System.out.println("response");
            System.out.println(response);

            // 1. 解析 JSON 数据
            Map<String, Object> resultMap = JSONUtil.parseObj(EntityUtils.toString(response.getEntity()));

            System.out.println("resultMap");
            System.out.println(resultMap);

            // 2. 获取 daily 数据（假设 daily 是一个 List<Map>）
            List<Map<String, Object>> dailyList = (List<Map<String, Object>>) resultMap.get("hourly");

            // 3. 使用 Hutool 的 BeanUtil 转换
            List<HourlyWeather> list = dailyList.stream()
                    .map(dailyMap -> BeanUtil.toBean(dailyMap, HourlyWeather.class))
                    .collect(Collectors.toList());

            log.info("网络请求成功！请求响应码为：{},响应结果值为：{}",resultMap.get("code"),resultMap.get("hourly"));

            return list;

        } catch (Exception e) {
            System.out.println(e);
            log.info("网络请求失败！请求api为{}，请求头{}，请求参数{},错误信息为：{}",api3,header,query,e.getMessage());
        }

        return Collections.emptyList();
    }

    @Override
    public Location getLocation(String longitude, String latitude) {


        Map<String,String> header = new HashMap<String,String>();
        header.put("X-QW-Api-Key",apiKy);

        Map<String,String> query = new HashMap<String,String>();
        query.put("location", latitude+','+longitude);

        log.info("请求配置信息： host:{},path:{},apiKy:{},query:{}",heFengHost,api4,apiKy,query);

        try {
            HttpResponse response = doGet(heFengHost,api4,header,query);

            System.out.println("response");
            System.out.println(response);

            // 1. 解析 JSON 数据
            Map<String, Object> resultMap = JSONUtil.parseObj(EntityUtils.toString(response.getEntity()));

            System.out.println("resultMap");
            System.out.println(resultMap);

            // 3. 使用 Hutool 的 BeanUtil 转换

            String locationJson = JSONUtil.parseObj(resultMap).getJSONArray("location").get(0).toString();
            Location locations =JSONUtil.toBean(locationJson, Location.class);

            log.info("网络请求成功！请求响应码为：{},响应结果值为：{}",resultMap.get("code"),resultMap.get("location"));

            return locations;

        } catch (Exception e) {
            System.out.println(e);
            log.info("网络请求失败！请求api为{}，请求头{}，请求参数{},错误信息为：{}",api3,header,query,e.getMessage());
        }

        return null;
    }
}
